const fs = require('fs')

// 回调函数形式
function getXiaoQiaoInfo(filePath: string, callback: (err?: Error, promiseData?: any) => void) {
  fs.readFile(filePath, (err: Error, data: string) => {
    if(err) {
      callback(err)
    } else {
      // const error = new Error('警告')
      callback(JSON.parse(data.toString()))
    }
  })
}
getXiaoQiaoInfo('./assets/15-promise.json', res => {
  console.log('res', res);
})

// promise形式
function getXiaoQiaoInfoAsync(filePath: string) : Promise<any> {
  return new Promise((res, rej) => {
    fs.readFile(filePath, (err: Error, data: string) => {
      if(err) {
        rej(err)
      } else {
        res(data)
      }
    })
  })
}

getXiaoQiaoInfoAsync('./assets/15-promise.json').then(res => {
  const data = JSON.parse(res.toString())
  console.log('data', data)
})

// promise.all()
// 通过 setTimeout 模 拟向 服务器 拉 取 数据
function fethUserInfo( userId: string): Promise<{}> {
  return new Promise( resolve => {
    setTimeout(() => {
      resolve({ userId });
    }, 1000);
  });
}
function fethCartInfo( userId: string): Promise<{}> {
  return new Promise( resolve => {
    setTimeout(() => {
      resolve({ userId });
    }, 1200);
  });
}
function fethGoodInfo(goodId: string): Promise<{}> {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve({ goodId });
    }, 1500);
  });
}
Promise.all([fethUserInfo(" 1"), fethCartInfo(" 2"), fethGoodInfo(" 233")])
.then(res => { console.log(res); });